package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;
import org.apache.struts.util.MessageResources;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.tags.attachFileTag;
import com.scalar.chiptrack.tags.InternalCommentsTag;
import com.scalar.chiptrack.alarms.Alarm;
import com.scalar.chiptrack.alarms.AlarmUser;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.actions.InternalCommentsAction;
import com.scalar.chiptrack.commons.dao.AttachFileDAO;
import com.scalar.chiptrack.commons.dao.InternalCommentsDAO;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.packingslip.PackingSlipComparator;
import com.scalar.chiptrack.sales.*;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.CustomerRelationshipDAO;
import com.scalar.chiptrack.sales.dao.EndUserDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.forms.ApproverOrderForm;
import com.scalar.chiptrack.sales.forms.SalesOrderForm;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;


// Balaram, on Jan 14, 2004

/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.28 $ $Date: 2011/03/01 16:56:51 $
 */

public final class SalesOrderAction extends ChipTrackAction
{

    private static final String ACTION_NAME = "/salesOrder.do";

    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        SalesOrderForm subform = ( SalesOrderForm ) form;
        HttpSession session = request.getSession ();

        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        String selectedCustomer = null;
        String action = request.getParameter ( "action" );

        if ( user == null )
        {
            if( "printView".equals ( action ) )
            {
                request.setAttribute ( "closeWindowAfterSessionExp", "true" );
			    return ( mapping.findForward( "printView" ) );
            }
            else{
                session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString ()+"&isSample="+request.getParameter("isSample"));
                return ( mapping.findForward ( "login" ) );
            }
        }
        int isSample = 1; //default set to salesOrder
        if ( ( request.getParameter ( "isSample" ) != null ) && ( !request.getParameter ( "isSample" ).equals ( "null" ) ) )
        {
            isSample = Integer.parseInt ( request.getParameter ( "isSample" ) );
        }
        HashMap<String, String> errors = new HashMap<String, String>();
        HashMap<String, String> info = new HashMap<String, String>();
        SalesOrder salesOrderFromMap = null;
        HashMap<String, SalesOrder>  salesOrderMap = ( HashMap<String, SalesOrder> ) session.getAttribute( "salesOrderMap" );
        if ( salesOrderMap == null )
        {
            salesOrderMap = new HashMap<String, SalesOrder>();
            session.setAttribute( "salesOrderMap", salesOrderMap );
        }
        selectedCustomer = request.getParameter ( "customerId" );
        selectedCustomer = ( selectedCustomer != null ) ? selectedCustomer.trim() : null;
        salesOrderFromMap = ( SalesOrder ) salesOrderMap.get( selectedCustomer );
        if( salesOrderFromMap == null )
        {
            if ( "NewSalesOrder".equalsIgnoreCase( action ) == false &&  "printView".equalsIgnoreCase( action ) == false )
            {
                errors.put( ERROR_SALES_ORDER_ALREADY_SAVED_FOR_SAME_CUSTOMER, null);
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                action = "NewSalesOrder";
            }
            else
            {
                salesOrderMap.put( selectedCustomer, new SalesOrder() );
            }
        }
        else
        {
            if ( subform.getOdmId() > 0 )
            {
                salesOrderFromMap.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) ) ;
            }
            else
            {
                salesOrderFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( subform.getCustomerId ()) ) ;
            }
        }
        if ( "NewSalesOrder".equals ( action ) )
        {
            try
            {
                Integer.parseInt( selectedCustomer );
            }
            catch ( NumberFormatException e )
            {
                errors.put ( "Could not load Customer details", null );
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                return mapping.findForward( "successSalesOrder" );
            }
            //Set the customer details for this selected customer...
            SalesOrder salesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( selectedCustomer );
            if ( salesOrderMap == null )
            {
                salesOrderMap = new HashMap();
            }
            salesOrderMap.put( selectedCustomer, salesOrder );
            session.setAttribute( "salesOrderMap", salesOrderMap );
            PropertyUtils.copyProperties ( subform, salesOrder );
            subform.setBillingAddress ( salesOrder.getBillingAddressAsObject() != null ?  salesOrder.getBillingAddressAsObject ().getAddressAsString () : "" );
            subform.setShippingAddress (  salesOrder.getShippingAddressAsObject () != null ?  salesOrder.getShippingAddressAsObject ().getAddressAsString () : "" );
            subform.setContactPerson ( salesOrder.getContactPerson () );
            if( isSample == 1)
            {
                subform.setSalesOrderNo ( SalesOrderDAO.loadAutomatedSalesOrderNo () );
                if ( "0".equals ( subform.getIsConsignmentSales() ) )
                {
                    subform.setSalesOrderNo( Constants.CONSIGNMENT_SALESORDER_NO_PREFIX + "-" + subform.getSalesOrderNo() ); //For Consignment adding prefix "C-"
                }
            }
            else
            {
                subform.setSalesOrderNo ( SalesOrderDAO.loadAutomatedSampleSalesOrderNo () );
            }
            if ( selectedCustomer != null )
            {
                subform.setCustomerId ( Integer.parseInt ( selectedCustomer ) );
            }
            //Set the default lineItems...
            ArrayList lineItems = getLineItems ( session, isSample);

            request.setAttribute ( "lineItems", lineItems );
            request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
            if ( subform.getShippingMethodName () != null )
            {
                subform.setShippingMethodName ( subform.getShippingMethodName ().trim () );
            }
            if ( subform.getShippingAccount () != null )
            {
                subform.setShippingAccount ( subform.getShippingAccount ().trim () );
            }
            request.setAttribute ( "Account", subform.getShippingMethodName () + "   #   " + subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingMethodName () + "   #   " + subform.getShippingAccount () );

            session.setAttribute ( "mktgParts", SalesOrderDAO.loadAllMarketingPartNumbers ());
            salesOrder.setMfgParts( SalesOrderDAO.loadAllManfacturingPartNosOfCustomerWithOutobsolete ( Integer.parseInt ( selectedCustomer ), isSample ) );
            //salesOrder.setMfgPartsWithComments( SalesOrderDAO.loadAllManfacturingPartNumbersWithComments ( Integer.parseInt ( selectedCustomer ), isSample ) );
            if ( ConfigManager.getBooleanProperty(ConfigManager.PROP_SHOW_SALES_LINEITEM_BASE_ORDER_QTY) )
            {
                salesOrder.setMfgPartsWithBaseOrderQty( SalesOrderDAO.loadManufacturingPartNumbersWithBaseOrderQty ( null,  Integer.parseInt ( selectedCustomer ) ) );
            }   
            salesOrder.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers( Integer.parseInt ( selectedCustomer ), subform.getOdmId(), isSample ) ) ;
            //salesOrder.setMfgPartsWithLabelNumbers( NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( Integer.parseInt ( selectedCustomer ), subform.getOdmId(), isSample ) );
            session.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );
            //load all Sales Persons,Sales Reps of the customer
            salesOrder.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( Integer.parseInt ( selectedCustomer ) ) ) ;
            salesOrder.setSalesReps( CustomerDAO.loadAllSalesRepsforCustomer(Integer.parseInt ( selectedCustomer ) ) ) ;
            salesOrder.setOdmList( CustomerRelationshipDAO.getAllOdmsForCustomer( selectedCustomer ) ) ;
            salesOrder.setEndCustomerList( CustomerRelationshipDAO.getAllEndCustomersForCustomer( selectedCustomer ) ) ;
            session.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
            session.setAttribute ( "freightInstructions", NewSalesOrderDAO.loadFreightInstructions( null ) );
            ContactPerson contactPerson = new ContactPerson();
            Address addressObject;
            addressObject = CustomerDAO.getAddress ( salesOrder.getBillingAddressId () );

            contactPerson.setContactPerson(subform.getCustomerName());
            contactPerson.setPhoneNumber(addressObject.getPhoneNumber());
            contactPerson.setCellNumber("");
            contactPerson.setFaxNumber(addressObject.getFaxNumber());
            contactPerson.setEmail(addressObject.getEmail());

            HashMap<String, ContactPerson> customerContactPersonMap = CustomerDAO.getContactPersonDetailsMap ( Integer.parseInt ( request.getParameter ( "customerId" ) ) );
            customerContactPersonMap.put(subform.getCustomerName(),contactPerson);
            salesOrder.setCustomerContactPersonMap( customerContactPersonMap );

            HashMap<String, String> billingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getBillingAddressId() , salesOrder.getBillingAddressAsObject ());
            addressObject.setContactPerson("");
            addressObject.setCellNumber("");
            billingAddressMap.put("",addressObject.getAddressAsString());
            HashMap<String, String> shippingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getShippingAddressId() , salesOrder.getShippingAddressAsObject ());
            Address shipAddress = CustomerDAO.getAddress ( salesOrder.getShippingAddressId () );
            shippingAddressMap.put("",shipAddress.getAddressWithoutContactPersonAsString());
            salesOrder.setBillingAddressMap( billingAddressMap );
            salesOrder.setShippingAddressMap( shippingAddressMap );

            session.setAttribute ( "allShippingTerms", subform.getAllShippingTerms () );
            session.setAttribute ( "allDeliveryTerms", subform.getAllDeliveryTerms() );
            //Set the shippingAddresses for the collection
            request.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );

            return ( mapping.findForward ( "salesOrder" ) );
        }
        else if ( "UpdateSalesOrder".equals ( action ) )
        {
            if ( !isTokenValid ( request ) )
            {
                errors.put ( ERROR_SALES_ORDER_ALREADY_SAVED, null );
            }

            resetToken ( request );
            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                saveToken ( request );
                return ( mapping.findForward ( "success" ) );
            }
            addNewSalesTaxState ( request, session, errors, subform );

            // Chekcing if the user has selected a new shipping address and if so then setting the shippingAddressID as the newShippingAddressID
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
            }
            subform.setShippingMethod ( subform.getShippingAccount () );
            salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
            request.setAttribute ( "salesOrderForm", subform );

            //Set the lineitems in the request,false is not to check for marketing limits
            ArrayList lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );

            request.setAttribute ( "lineItems", lineItems );
            request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );

            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

            subform.setSalesTaxAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "salesTax" ) ) );
            subform.setSubTotalAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "subTotal" ) ) );
            subform.setOrderTotalAsDouble ( subform.getSubTotalAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSalesTaxAsDouble () );

            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );

            errors = ( HashMap ) request.getAttribute ( "Errors" );
            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
            }
            //saveErrors(request, errors);
            saveToken ( request );
            return ( mapping.findForward ( "salesOrder" ) );
        }
        else if ( "SubmitSalesOrder".equals ( action ) )
        {
            int index1 = 0;
            String shippingMethodName = "";
            if ( subform.getShippingAddressId () == -1 && ( session.getAttribute ( "newShippingAddressId" ) != null ))
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
                session.removeAttribute ( "newShippingAddressId" );
            }
            addNewShippingMethod ( request, session, errors, info, subform, salesOrderFromMap );
            addNewSalesTaxState ( request, session, errors, subform );
            addNewShippingTerms ( request, session, errors, info, subform );
            addNewDeliveryTerms ( request, session, errors, info, subform );
            addNewShippingInstructions( request, session, errors, info, subform );
            addNewFreightInstructions( request, session, errors, info, subform );

            //Set the form values and lineitems values, to show in the confirmation page
            session.setAttribute ( "salesOrderForm", subform );

            //Set the lineitems values , true for check for marketing limits
            ArrayList lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info, true, isSample );

            session.setAttribute ( "lineItems", lineItems );
            session.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
            //To get proper shipping method
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );

            subform.setTotalQty ( Integer.parseInt ( ( String ) request.getAttribute ( "totalQty" ) ) );
            subform.setSalesTaxAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "salesTax" ) ) );
            subform.setSubTotalAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "subTotal" ) ) );
            subform.setOrderTotalAsDouble ( subform.getSubTotalAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSalesTaxAsDouble () );

            session.setAttribute ( "totalQty", request.getAttribute ( "totalQty" ) );
            session.setAttribute ( "salesTax", request.getAttribute ( "salesTax" ) );
            session.setAttribute ( "subTotal", request.getAttribute ( "subTotal" ) );
            session.setAttribute ( "orderTotal", Double.toString ( subform.getSalesTaxAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSubTotalAsDouble () ) );
            session.setAttribute ( "tempShippingMethod", subform.getShippingMethod () );

            subform.setOdm(CustomerDAO.getCustomerName( null,subform.getOdmId()));
            subform.setEndCustomer( CustomerDAO.getCustomerName( null,subform.getEndCustomerId() ));
            String salesOrderNos = null;
            if ( subform.getCustomerPO() != null && subform.getCustomerPO().trim().length() > 0 )
            {
                salesOrderNos = NewSalesOrderDAO.getSalesOrderNoForCustomerPO( null, subform.getCustomerPO().trim(), subform.getCustomerId(), subform.getSalesOrderNo() );
            }
            if ( salesOrderNos != null && salesOrderNos.trim().length() > 0 )
            {
                if ( salesOrderNos.indexOf(",") > 0 )
                {
                    info.put( "Warning : Sales Orders ( "+salesOrderNos+" ) are already exists for this PO. Do you want to create another ?", null );
                }
                else
                {
                    info.put( "Warning : Sales Order ( "+salesOrderNos+" ) is already generated for this PO. Do you want to create another ?", null );
                }
            }
            errors = ( HashMap ) request.getAttribute ( "Errors" );
            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                return ( mapping.findForward ( "salesOrder" ) );
            }

            info = ( HashMap ) request.getAttribute ( "Info" );
            if ( !info.isEmpty () )
            {
                request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
            }

            saveToken ( request );
            return ( mapping.findForward ( "confirmOrder" ) );
        }
        else if ( "printView".equals ( action ) )
        {
            ApproverOrderForm approverOrderForm = new ApproverOrderForm ();
            SalesOrder salesOrder = new SalesOrder ();
            SalesOrderForm salesOrderForm = ( SalesOrderForm ) session.getAttribute ( "salesOrderForm" );
            PropertyUtils.copyProperties ( salesOrder, salesOrderForm );
            SalesOrderDAO.loadClientAddress ( salesOrder );
            salesOrder.setShippingAddressAsObject( CustomerDAO.getAddressWithContactPersonDetails( salesOrder.getShippingAddressId(), salesOrder.getShippingContactPerson()) );
            salesOrder.setBillingAddressAsObject( CustomerDAO.getAddressWithContactPersonDetails( salesOrder.getBillingAddressId(), salesOrder.getBillingContactPerson(), salesOrder.getCustomerId() ) ); // modified by sujan on 16th dec 2004  'added the new parameter customerId'
            salesOrder.setShippingAccount ( ( String ) session.getAttribute ( "tempShippingMethod" ) );
            salesOrder.setTotalQty ( ( String ) session.getAttribute ( "totalQty" ) );
            salesOrder.setFinalSubTotal ( Double.parseDouble ( ( String ) session.getAttribute ( "subTotal" ) ) );
            salesOrder.setFinalSalesTax ( Double.parseDouble ( ( String ) session.getAttribute ( "salesTax" ) ) );
            salesOrder.setFinalOrderTotal ( Double.parseDouble ( ( String ) session.getAttribute ( "orderTotal" ) ) );

            approverOrderForm.setSalesOrderId ( salesOrderForm.getSalesOrderId () );
            approverOrderForm.setSalesOrderNo ( salesOrderForm.getSalesOrderNo () );

            String clientaddressId =  UserDAO.getClientAddressId();
            String addressId = null;
            String clientname = null;

            int finalAddressId = 0;
            if(clientaddressId != null)
            {
                StringTokenizer st = new StringTokenizer(clientaddressId,"@");
                try
                {
                    addressId = st.nextToken();
                    clientname = st.nextToken();
                }catch(NoSuchElementException e)
                {
                     clientname  = "";
                }
            }
            if(addressId  != null)
            {
                finalAddressId = Integer.parseInt(addressId);
            }
            Address clientAddress= UserDAO.loadClientAddressDetails( null , finalAddressId );
            salesOrder.setClientAddressAsObject(clientAddress);
            String clientAddress1 = SalesOrder.getClientAddressAsString(clientAddress);
            salesOrder.setClientAddress(clientAddress1);
            salesOrder.setClientName(clientname);
            Customer customer = new Customer();
            customer.setCustomerId( salesOrder.getCustomerId() );
            CustomerDAO.getCustomerDetailsForAcknowledgement( null, customer );
            request.setAttribute ( "customer", customer );

            approverOrderForm.setSalesOrder ( salesOrder );
            request.setAttribute ( "approverOrderForm", approverOrderForm );
            request.setAttribute ( "lineItems", session.getAttribute ( "lineItems" ) );
            ArrayList list = (ArrayList) request.getAttribute("lineItems");
            if ( list != null )
            {
                Collections.sort (list , new PackingSlipComparator () );
            }
            request.setAttribute ( "termsAndConditions", SalesDAO.loadTermsAndConditionsAsList () );
            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals( list ) );
            return ( mapping.findForward ( "printView" ) );
        }
        else if ( "EditSalesOrder".equals ( action ) )
        {
            if ( !isTokenValid ( request ) )
            {
                errors.put ( ERROR_SALES_ORDER_ALREADY_SAVED, null );
            }
            resetToken ( request );
            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                saveToken ( request );
                if ( user.getUserType() == Constants.USER_TYPE_CUSTOMER )
                {
                    return ( mapping.findForward ( "changeOrderSearch" ) );
                }
                else
                {
                    return ( mapping.findForward ( "successSalesOrder" ) );
                }
            }
            subform.setShippingMethod ( subform.getShippingAccount () );
            salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
            String hdnShippingMethodName = request.getParameter ( "hdnShippingMethodName" );
            String hdnshippingAccount = request.getParameter ( "hdnshippingAccount" );
            request.setAttribute ( "Account", hdnshippingAccount );
            request.setAttribute ( "Method", hdnshippingAccount );
            salesOrderFromMap.setMfgParts( SalesOrderDAO.loadAllManfacturingPartNosOfCustomerWithOutobsolete ( Integer.parseInt ( selectedCustomer ), isSample )  );
            request.setAttribute ( "lineItems", request.getAttribute ( "lineItems" ) );
            session.setAttribute ( "maxLineItemNo", session.getAttribute ( "maxLineItemNo" ) );
            request.setAttribute ( "salesOrderForm", session.getAttribute ( "salesOrderForm" ) );
            saveToken ( request );
            return ( mapping.findForward ( "salesOrder" ) );
        }
        else if ( "loadEndUserDetails".equals ( action ) )
        {
            String endUserId = request.getParameter ( "endUserId" );
            ArrayList lineItems = null;
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
            }
            if ( endUserId != null )
            {
                if ( "".equals ( endUserId.trim () ) )
                {
                    SalesOrder salesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );
                    subform.setContactPersons ( salesOrder.getContactPersons () );
                    subform.setContactPersonsForBillingAddress ( salesOrder.getContactPersonsForBillingAddress () );
                    subform.setContactPersonsForShippingAddress ( salesOrder.getContactPersonsForShippingAddress () );
                    subform.setBillingAddress ( SalesOrder.getAddressAsString ( salesOrder.getBillingAddressAsObject () ) );
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( salesOrder.getShippingAddressAsObject () ) );

                    HashMap billingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getBillingAddressId() , salesOrder.getBillingAddressAsObject ());
                    Address address= CustomerDAO.getAddress ( salesOrder.getBillingAddressId () );
                    address.setContactPerson(subform.getCustomerName());
                    address.setCellNumber("");
                    billingAddressMap.put("",SalesOrder.getAddressAsString(address));
                    session.setAttribute ( "billingAddressMap", billingAddressMap  );
                    HashMap shippingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getShippingAddressId() , salesOrder.getShippingAddressAsObject ());
                    Address shipAddress = CustomerDAO.getAddress ( salesOrder.getShippingAddressId () );
                    shipAddress.setContactPerson("");
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                    shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    session.setAttribute ( "shippingAddressMap", shippingAddressMap );
                    subform.setShippingAddresses ( salesOrder.getShippingAddresses () );
                    subform.setBillingAddresses ( salesOrder.getBillingAddresses () );
                    subform.setEndUser ( "" );
                    subform.setOdmId( -1 );
                    subform.setBillingAddressId ( salesOrder.getBillingAddressId () );
                    subform.setShippingAddressId ( salesOrder.getShippingAddressId () );
                    subform.setBillingContactPerson ( salesOrder.getBillingContactPerson () );
                    subform.setShippingContactPerson ( salesOrder.getShippingContactPerson () );

                    session.setAttribute ( "mfgPartsWithCustomerPartNos", NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers( subform.getCustomerId(), subform.getOdmId(), isSample ) ) ;
                    session.setAttribute ( "mfgPartsWithLabelNumbers", NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( salesOrder.getCustomerId (), subform.getOdmId(), isSample ) );
                }
                else
                {
                    EndUser endUser = EndUserDAO.getEndUserDetails ( Integer.parseInt ( endUserId ) );
                    subform.setContactPersonsForBillingAddress(CustomerDAO.getAllContactPersonsForAddress( endUser.getDefaultBillingAddressId() ));
                    subform.setContactPersonsForShippingAddress(CustomerDAO.getAllContactPersonsForAddress( endUser.getDefaultShippingAddressId() ));
                    subform.setEndUser ( endUser.getEndUserName () );
                    subform.setOdmId( -1 );
                    ArrayList shippingAddresses = endUser.getShippingLocations ();
                    shippingAddresses.add ( 0, endUser.getShippingAddress () );

                    subform.setBillingAddressId ( endUser.getDefaultBillingAddressId () );
                    subform.setShippingAddressId ( endUser.getDefaultShippingAddressId () );
                    subform.setBillingAddress ( SalesOrder.getAddressAsString ( endUser.getBillingAddress () ) );
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( endUser.getShippingAddress () ) );
                    SalesOrder salesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );

                    subform.setBillingContactPerson(endUser.getBillingContactPersonObject().getContactPerson());
                    subform.setShippingContactPerson(endUser.getShippingContactPersonObject().getContactPerson());

                    subform.setContactPersons ( salesOrder.getContactPersons () );
                    HashMap billingAddressMap = CustomerDAO.getAddressDetailsMap (  subform.getBillingAddressId() , endUser.getBillingAddress ());
                    Address customerAddressObject = CustomerDAO.getAddress ( salesOrder.getBillingAddressId () );

                    Address billAddress = CustomerDAO.getAddress ( endUser.getDefaultBillingAddressId () );

                    if (billAddress !=  null)
                    {
                        String billContactPersonName = billAddress.getContactPerson();
                        billAddress.setContactPerson(subform.getCustomerName());
                        billAddress.setPhoneNumber(customerAddressObject.getPhoneNumber());
                        billAddress.setCellNumber("");
                        billAddress.setFaxNumber(customerAddressObject.getFaxNumber());
                        billAddress.setEmail(customerAddressObject.getEmail());
                        billingAddressMap.put("",SalesOrder.getAddressAsString(billAddress));
                        session.setAttribute ( "billingAddressMap", billingAddressMap  );
                        if( billContactPersonName == null || billContactPersonName.trim().length() == 0  || billContactPersonName.equals(subform.getCustomerName() ) )
                        {
                            subform.setBillingAddress(SalesOrder.getAddressAsString(billAddress));
                        }
                    }

                    HashMap shippingAddressMap = CustomerDAO.getAddressDetailsMap ( subform.getShippingAddressId() , endUser.getShippingAddress ());
                    Address shipAddress = CustomerDAO.getAddress(endUser.getDefaultShippingAddressId());
                    shipAddress.setContactPerson("");
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                    shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    session.setAttribute ( "shippingAddressMap", shippingAddressMap  );
                    Address address = endUser.getBillingAddress();

                    String billAddressWithoutContactPerson = getAddressAsString(address);

                    address = endUser.getShippingAddress();

                    String shipAddressWithoutContactPerson = getAddressAsString(address);

                    if ( billAddressWithoutContactPerson.trim ().equals ( "" ) )
                    {
                        subform.setBillingAddressId ( salesOrder.getBillingAddressId () );
                        Address billingAddress = salesOrder.getBillingAddressAsObject ();

                        subform.setBillingAddress ( SalesOrder.getAddressAsString ( billingAddress ) );
                        subform.setContactPersonsForBillingAddress ( salesOrder.getContactPersonsForBillingAddress () );
                        subform.setBillingContactPerson ( salesOrder.getBillingContactPerson () );

                        billingAddress = CustomerDAO.getAddress ( salesOrder.getBillingAddressId () );
                        billingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getBillingAddressId() , salesOrder.getBillingAddressAsObject () );
                        billingAddress.setContactPerson(subform.getCustomerName());
                        billingAddress.setCellNumber("");
                        billingAddressMap.put("",SalesOrder.getAddressAsString(billingAddress));
                        session.setAttribute ( "billingAddressMap", billingAddressMap  );
                    }
                    if( shipAddressWithoutContactPerson.trim().equals("") )
                    {
                        subform.setShippingAddressId ( salesOrder.getShippingAddressId () );
                        Address shippingAddress = salesOrder.getShippingAddressAsObject();

                        subform.setShippingAddress ( SalesOrder.getAddressAsString ( shippingAddress ) );
                        subform.setShippingAddressId( salesOrder.getShippingAddressId() );
                        subform.setContactPersonsForShippingAddress ( salesOrder.getContactPersonsForShippingAddress () );
                        subform.setShippingContactPerson(salesOrder.getShippingContactPerson());
                        shippingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getShippingAddressId() , salesOrder.getShippingAddressAsObject ());
                        shipAddress = CustomerDAO.getAddress ( salesOrder.getShippingAddressId () );
                        shipAddress.setContactPerson("");
                        shipAddress.setPhoneNumber("");
                        shipAddress.setCellNumber("");
                        shipAddress.setFaxNumber("");
                        shipAddress.setEmail("");
                        shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                        session.setAttribute ( "shippingAddressMap", shippingAddressMap );
                        subform.setShippingAddresses ( salesOrder.getShippingAddresses () );
                    }
                    //To get the customer default shipping address when the end user is selected for the quotation.
                    shippingAddresses.add ( CustomerDAO.getAddress ( SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId() ) ) );
                    subform.setShippingAddresses ( loadShippingAddresses ( shippingAddresses ) );
                    session.setAttribute ( "mfgPartsWithCustomerPartNos", EndUserDAO.loadManfacturingPartNumbersWithEndUserPartNos ( Integer.parseInt ( endUserId ) ) );
                    session.setAttribute ( "mfgPartsWithLabelNumbers",EndUserDAO.loadManfacturingPartNumbersWithEndUserLabelNumbers ( Integer.parseInt ( endUserId ) ) );
                }
                subform.setIsEndCustomerShipAddress( false );
            }
            session.setAttribute ( "contactPersons", subform.getContactPersons () );
            session.setAttribute ( "billingAddressContactPersons", subform.getContactPersonsForBillingAddress() );
            session.setAttribute ( "shippingAddressContactPersons", subform.getContactPersonsForShippingAddress() );

            int someValue = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample ).size ();

            if ( someValue == 0 )
            {
                lineItems = getLineItems ( session, isSample);
                request.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
                session.setAttribute ( "mfgPartsWithComments", SalesOrderDAO.loadAllManfacturingPartNumbersWithComments ( subform.getCustomerId (), isSample ) );
            }
            else
            {
                lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );

                /*if ( "".equals ( endUserId ) )
                {
                    SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, lineItems, subform.getCustomerId (), subform.getOdmId() );
                    NewSalesOrderDAO.loadOdmLabelNumbersForLineItems ( null, lineItems, subform.getCustomerId (), subform.getOdmId() );
                }
                else
                {
                    SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, lineItems, Integer.parseInt ( endUserId ) );
                }*/

                session.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
                session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
                subform.setSalesTaxAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "salesTax" ) ) );
                subform.setSubTotalAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "subTotal" ) ) );
                subform.setOrderTotalAsDouble ( subform.getSubTotalAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSalesTaxAsDouble () );
            }
            session.setAttribute ( "shippingMethods", CustomerDAO.loadSalesOrderShippingMethods( subform.getCustomerId() ) );
            session.setAttribute ( "shippingAddresses", subform.getShippingAddresses () );
            session.setAttribute ( "salesPersons",CustomerDAO.loadAllSalesPersonsforCustomer(subform.getCustomerId () ) ) ;
            session.setAttribute ( "mktgParts", SalesOrderDAO.loadAllMarketingPartNumbers () );
            session.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );
            session.setAttribute ( "mfgParts", SalesOrderDAO.loadAllManfacturingPartNosOfCustomerWithOutobsolete ( subform.getCustomerId (), isSample ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            request.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );
            return ( mapping.findForward ( "salesOrder" ) );
        }
        else if ( "loadODMDetails".equalsIgnoreCase( action ))
        {
            String odmId = request.getParameter ( "odmId" );
            ArrayList lineItems = null;
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) ) {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
            }
            if ( odmId != null )
            {
                if ( "-1".equals ( odmId.trim () ) )
                {
                    SalesOrder salesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );
                    subform.setContactPersons ( salesOrder.getContactPersons () );
                    subform.setContactPersonsForBillingAddress ( salesOrder.getContactPersonsForBillingAddress () );
                    subform.setContactPersonsForShippingAddress ( salesOrder.getContactPersonsForShippingAddress () );
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( salesOrder.getShippingAddressAsObject () ) );
                    HashMap shippingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getShippingAddressId() , salesOrder.getShippingAddressAsObject ());
                    Address shipAddress = CustomerDAO.getAddress ( salesOrder.getShippingAddressId () );
                    shipAddress.setContactPerson("");
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                    shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    salesOrderFromMap.setShippingAddressMap( shippingAddressMap );
                    subform.setShippingAddresses ( salesOrder.getShippingAddresses () );
                    subform.setBillingAddresses ( salesOrder.getBillingAddresses () );
                    subform.setEndUser ( "" );
                    subform.setShippingAddressId ( salesOrder.getShippingAddressId () );
                    subform.setShippingContactPerson ( salesOrder.getShippingContactPerson () );
                    salesOrderFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( Integer.parseInt ( selectedCustomer ) ) ) ;
                    salesOrderFromMap.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers( Integer.parseInt ( selectedCustomer ), subform.getOdmId(), isSample ) ) ;
                    salesOrderFromMap.setMfgPartsWithLabelNumbers( NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( Integer.parseInt ( selectedCustomer ), subform.getOdmId(), isSample ) );
                    salesOrderFromMap.setShippingMethods( CustomerDAO.loadAllShippingMethods( subform.getCustomerId() ) );
                }
                else
                {
                    subform.setEndUser ( "" );
                    subform.setEndUserId("");
                    SalesOrder salesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );
                    SalesOrder odmSalesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( odmId );
                    Address customerShippingAddress = salesOrder.getShippingAddressAsObject();
                    subform.setContactPersonsForBillingAddress( salesOrder.getContactPersonsForBillingAddress () );
                    subform.setContactPersonsForShippingAddress( odmSalesOrder.getContactPersonsForShippingAddress () );
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( odmSalesOrder.getShippingAddressAsObject () ) );
                    subform.setShippingContactPerson( odmSalesOrder.getShippingContactPerson () );
                    subform.setShippingAddressId ( odmSalesOrder.getShippingAddressId () );
                    ArrayList shippingAddresses = odmSalesOrder.getShippingAddresses();
                    subform.setContactPersons ( salesOrder.getContactPersons () );
                    HashMap shippingAddressMap = CustomerDAO.getAddressDetailsMap ( odmSalesOrder.getShippingAddressId() , odmSalesOrder.getShippingAddressAsObject ());
                    Address shipAddress = CustomerDAO.getAddress(odmSalesOrder.getShippingAddressId());
                    shipAddress.setContactPerson("");
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                    shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    salesOrderFromMap.setShippingAddressMap( shippingAddressMap );

                    Address address = odmSalesOrder.getShippingAddressAsObject();
                    String shipAddressWithoutContactPerson = getAddressAsString(address);

                    if( shipAddressWithoutContactPerson.trim().equals("") )
                    {
                        subform.setShippingAddressId ( salesOrder.getShippingAddressId () );
                        subform.setShippingAddress ( SalesOrder.getAddressAsString ( customerShippingAddress ) );
                        subform.setContactPersonsForShippingAddress ( salesOrder.getContactPersonsForShippingAddress () );
                        subform.setShippingContactPerson(salesOrder.getShippingContactPerson());
                        shippingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getShippingAddressId() , salesOrder.getShippingAddressAsObject ());
                        shipAddress = CustomerDAO.getAddress ( salesOrder.getShippingAddressId () );
                        shipAddress.setContactPerson("");
                        shipAddress.setPhoneNumber("");
                        shipAddress.setCellNumber("");
                        shipAddress.setFaxNumber("");
                        shipAddress.setEmail("");
                        shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                        salesOrderFromMap.setShippingAddressMap( shippingAddressMap );
                        request.setAttribute ( "shippingAddressMap", shippingAddressMap );
                    }
                    ArrayList defaultShippingAddress = new ArrayList();
                    defaultShippingAddress.add( customerShippingAddress );

                    ArrayList farmatedDefualtShippingAddress = loadShippingAddresses ( defaultShippingAddress );

                    for ( int i = 0; i < farmatedDefualtShippingAddress.size(); i++ )
                    {
                        LabelValueBean  s = ( LabelValueBean ) farmatedDefualtShippingAddress.get( i );
                        shippingAddresses.add( s );
                    }
                    subform.setShippingAddresses ( shippingAddresses );
                    subform.setBillingAddresses ( salesOrder.getBillingAddresses() );
                    salesOrderFromMap.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers( Integer.parseInt ( selectedCustomer ), subform.getOdmId(), isSample ) ) ;
                    salesOrderFromMap.setMfgPartsWithLabelNumbers( NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( Integer.parseInt ( selectedCustomer ), subform.getOdmId(), isSample ) );
                    salesOrderFromMap.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), Integer.parseInt( odmId) ) ) ;
                    salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) );
                }
                subform.setIsEndCustomerShipAddress( true );
            }
            salesOrderFromMap.setContactPersons( subform.getContactPersons () );
            salesOrderFromMap.setContactPersonsForBillingAddress( subform.getContactPersonsForBillingAddress() );
            salesOrderFromMap.setContactPersonsForShippingAddress( subform.getContactPersonsForShippingAddress() );
            salesOrderFromMap.setShippingAddresses( subform.getShippingAddresses () );
            salesOrderFromMap.setBillingAddresses( subform.getBillingAddresses () );

            int someValue = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample ).size ();

            if ( someValue == 0 )
            {
                lineItems = getLineItems ( session, isSample);
                request.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
            }
            else
            {
                lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );

                session.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
                session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
                subform.setSalesTaxAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "salesTax" ) ) );
                subform.setSubTotalAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "subTotal" ) ) );
                subform.setOrderTotalAsDouble ( subform.getSubTotalAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSalesTaxAsDouble () );
            }
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            request.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );
            return ( mapping.findForward ( "salesOrder" ) );
        } else if ("loadBillingAddress".equals(action))     {
            if ((subform.getShippingAddressId() == -1) && (session.getAttribute("newShippingAddressId") != null)) {
                subform.setShippingAddressId(Integer.parseInt((String) session.getAttribute("newShippingAddressId")));
                Address address = CustomerDAO.getAddress(subform.getShippingAddressId());
                loadShippingAddress(address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap);
            }
            int billingAddressId = subform.getBillingAddressId();

            Address billingAddress = CustomerDAO.getAddressWithContactPersonDetails(billingAddressId);
            HashMap billingAddressMap = new HashMap();
            if (billingAddress != null) {
                subform.setBillingContactPerson(billingAddress.getContactPerson());
                subform.setBillingAddress(billingAddress.getAddressAsString());
                billingAddressMap = CustomerDAO.getAddressDetailsMap(billingAddressId, billingAddress);
                billingAddressMap.put("", billingAddress.getAddressWithoutContactPersonAsString());
            }
            salesOrderFromMap.setBillingAddressMap(billingAddressMap);
            salesOrderFromMap.setContactPersonsForBillingAddress(CustomerDAO.getAllContactPersonsForAddress(billingAddressId));
            salesOrderFromMap.setShippingMethods(CustomerDAO.loadShippingMethodsForCustomerAndOdm(subform.getCustomerId(), subform.getOdmId()));
            ArrayList lineItems = null;

            int someValue = loadLineItems(request, subform.getCustomerId(), errors, info, false, isSample).size();
            if (someValue == 0) {
                lineItems = getLineItems(session, isSample);
                request.setAttribute("lineItems", lineItems);
                request.setAttribute("lineItemsWithSubtotals", loadLineItemsWithSubTotals(lineItems));
            } else {
                lineItems = loadLineItems(request, subform.getCustomerId(), errors, info, false, isSample);
                session.setAttribute("lineItems", lineItems);
                request.setAttribute("lineItemsWithSubtotals", loadLineItemsWithSubTotals(lineItems));
                session.setAttribute("maxLineItemNo", request.getAttribute("maxLineItemNo"));

                subform.setSalesTaxAsDouble(Double.parseDouble((String) request.getAttribute("salesTax")));
                subform.setSubTotalAsDouble(Double.parseDouble((String) request.getAttribute("subTotal")));
                subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble() + subform.getFrieghtAsDouble() + subform.getMiscAsDouble() + subform.getSalesTaxAsDouble());
            }

            request.setAttribute("Account", subform.getShippingAccount());
            request.setAttribute("Method", subform.getShippingAccount());
            request.setAttribute("salesOrderForm", subform);
            saveToken(request);
            return (mapping.findForward("salesOrder"));
        }
        else if ( "loadShippingAddress".equals ( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
            }
            int shippingAddressId = subform.getShippingAddressId();

            Address shipAddress = CustomerDAO.getAddressWithContactPersonDetails ( shippingAddressId );
            HashMap shippingAddressMap = new HashMap();
            if(shipAddress != null)
            {
                subform.setShippingContactPerson( shipAddress.getContactPerson() );
                subform.setShippingAddress ( shipAddress.getAddressAsString ( ));
                shippingAddressMap = CustomerDAO.getAddressDetailsMap ( shippingAddressId, shipAddress);
                shippingAddressMap.put("",shipAddress.getAddressWithoutContactPersonAsString());
            }
            salesOrderFromMap.setShippingAddressMap( shippingAddressMap );
            salesOrderFromMap.setContactPersonsForShippingAddress( CustomerDAO.getAllContactPersonsForAddress(  shippingAddressId ) );
            salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
            ArrayList lineItems = null;

            int someValue = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample ).size ();
            if ( someValue == 0 )
            {
                lineItems = getLineItems ( session, isSample);
                request.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
            }
            else
            {
                lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );
                session.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
                session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

                subform.setSalesTaxAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "salesTax" ) ) );
                subform.setSubTotalAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "subTotal" ) ) );
                subform.setOrderTotalAsDouble ( subform.getSubTotalAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSalesTaxAsDouble () );
            }

            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            request.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );
            return ( mapping.findForward ( "salesOrder" ) );
        } // End of loadShippingAddress
        else if ( "loadShippingInstructions".equals ( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
            }
            ArrayList lineItems = null;
            subform.setShippingInstructions ( NewSalesOrderDAO.loadSelectedShippingInstructions( null, subform.getShippingInstructionsId() ) );

            int someValue = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample ).size ();
            if ( someValue == 0 )
            {
                lineItems = getLineItems ( session, isSample);
                request.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
            }
            else
            {
                lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );
                session.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
                session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

                subform.setSalesTaxAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "salesTax" ) ) );
                subform.setSubTotalAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "subTotal" ) ) );
                subform.setOrderTotalAsDouble ( subform.getSubTotalAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSalesTaxAsDouble () );
            }
            salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            request.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );
            return ( mapping.findForward ( "salesOrder" ) );
        } // End of loadShippingInstructions
        else if ( "loadEndCustomerDefualtShippingAddress".equals ( action ) )
        {
            ArrayList shippingList = new ArrayList();
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, shippingList, salesOrderFromMap );
            }
            salesOrderFromMap.setShippingAddresses(shippingList);
            int shippingAddressId = 0 ;
            if ( subform.getIsEndCustomerShipAddress() == false )
            {
                NewSalesOrderDAO.loadCustomerAddressesOfType(shippingList, subform.getCustomerId(), "Shipping");
                shippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId () );
            }
            else
            {
                if ( subform.getOdmId() > 0 )
                {
                    NewSalesOrderDAO.loadCustomerAddressesOfType(shippingList, subform.getOdmId(), "Shipping");
                    shippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getOdmId () );
                }
                else
                {
                    NewSalesOrderDAO.loadCustomerAddressesOfType(shippingList, subform.getCustomerId(), "Shipping");
                    shippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId () );
                }
            }
            String formContactPerson = null;
            if ( NewSalesOrderDAO.isAddressIdExists( shippingList, subform.getShippingAddressId() ) )
            {
                formContactPerson = subform.getShippingContactPerson();
                shippingAddressId = subform.getShippingAddressId();
            }
            else
            {
                subform.setShippingAddressId(shippingAddressId);
            }

            Address shipAddress = CustomerDAO.getAddress ( shippingAddressId );
            HashMap shippingAddressMap = new HashMap();
            if(shipAddress != null)
            {
                /*String shipAddressWithoutContactPerson = getAddressAsString( shipAddress );
                if ( "".equals( shipAddressWithoutContactPerson.trim() ) )
                {
                    int defaultShippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId () );
                    if ( defaultShippingAddressId != shippingAddressId )
                    {
                        shippingAddressId = defaultShippingAddressId;
                        subform.setShippingAddressId( shippingAddressId);
                        shipAddress = CustomerDAO.getAddress ( shippingAddressId );
                        subform.setShippingContactPerson( shipAddress.getContactPerson() );
                        formContactPerson = null;
                    }
                }*/
                if ( formContactPerson != null )
                {
                    subform.setShippingContactPerson( formContactPerson );
                }
                else
                {
                    subform.setShippingContactPerson( shipAddress.getContactPerson() );
                }
                ContactPerson shippingContactPerson = CustomerDAO.getAddressContactPersonDetails (shippingAddressId , subform.getShippingContactPerson());
                if( shippingContactPerson != null )
                {
                    shipAddress.setContactPerson(shippingContactPerson.getContactPerson());
                    shipAddress.setPhoneNumber(shippingContactPerson.getPhoneNumber());
                    shipAddress.setCellNumber(shippingContactPerson.getCellNumber());
                    shipAddress.setFaxNumber(shippingContactPerson.getFaxNumber());
                    shipAddress.setEmail(shippingContactPerson.getEmail());
                }
                else
                {
                    shipAddress.setContactPerson( "" );
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                }
                subform.setShippingAddress ( shipAddress.getAddressAsString ());
                shippingAddressMap = CustomerDAO.getAddressDetailsMap ( shippingAddressId, shipAddress);
                shippingAddressMap.put("",shipAddress.getAddressWithoutContactPersonAsString());
            }
            salesOrderFromMap.setShippingAddressMap( shippingAddressMap );
            salesOrderFromMap.setContactPersonsForShippingAddress( CustomerDAO.getAllContactPersonsForAddress(  shippingAddressId ) );
            ArrayList lineItems = null;
            int someValue = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample ).size ();
            if ( someValue == 0 )
            {
                lineItems = getLineItems ( session, isSample);
                request.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
            }
            else
            {
                lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );
                session.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
                session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

                subform.setSalesTaxAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "salesTax" ) ) );
                subform.setSubTotalAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "subTotal" ) ) );
                subform.setOrderTotalAsDouble ( subform.getSubTotalAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSalesTaxAsDouble () );
            }
            salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
            salesOrderFromMap.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers( subform.getCustomerId (), subform.getOdmId(), isSample ) ) ;
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            request.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );
            return ( mapping.findForward ( "salesOrder" ) );
        } // End of loadEndCustomerDefualtShippingAddress
        else if ( "ConfirmSalesOrder".equals ( action ) )
        {
            if ( !isTokenValid ( request ) )
            {
                errors.put ( ERROR_SALES_ORDER_ALREADY_SAVED, null );
            }
            resetToken ( request );
            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                saveToken ( request );
                if ( user.getUserType() == Constants.USER_TYPE_CUSTOMER )
                {
                    return ( mapping.findForward ( "changeOrderSearch" ) );
                }
                else
                {
                    return ( mapping.findForward ( "successSalesOrder" ) );
                }
            }

            SalesOrder salesOrder = new SalesOrder ();
            PropertyUtils.copyProperties ( salesOrder, ( SalesOrderForm ) session.getAttribute ( "salesOrderForm" ) );

            String method = "";
            String account = "";
            String temp = salesOrder.getShippingAccount ();
            account = temp;
            if ( temp != null )
            {
                int index1 = temp.indexOf ( "#" );

                if ( index1 != -1 && index1 != 0 )
                {
                    method = temp.substring ( 0, index1 ).trim ();
                    account = temp.substring ( index1 + 1, temp.length () ).trim ();
                }
            }
            salesOrder.setShippingAccount ( account );
            String methodName = salesOrder.getShippingMethodName ();
            if( methodName != null )
            {
                int index = methodName.indexOf ( "#" );
                if ( index != -1 && index != 0 )
                {
                    salesOrder.setShippingMethodName ( methodName.substring ( 0, index ).trim () );
                }
            }
            if ( SalesOrderDAO.isSalesOrderNoExists ( salesOrder.getSalesOrderNo () ) )
            {
                errors.put ( ERROR_SALES_ORDER_NO_ALREADY_EXISTS, null );
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                request.setAttribute ( "salesOrderForm", session.getAttribute ( "salesOrderForm" ) );
                request.setAttribute ( "lineItems", request.getAttribute ( "lineItems" ) );
                session.setAttribute ( "maxLineItemNo", session.getAttribute ( "maxLineItemNo" ) );
                request.setAttribute ( "Account", subform.getShippingAccount () );
                request.setAttribute ( "Method", subform.getShippingAccount () );
                request.setAttribute ( "customerId", "" + subform.getCustomerId () );
                saveToken ( request );
                return ( mapping.findForward ( "salesOrder" ) );
            }
            //Ends Here

            DBTransaction dbTransaction = null;
            boolean success             = false;
            Alarm alarm                 = null;
            String status               = null;
            String holdsAuditTrail      = "";
            String salesOrderStatus     = null;
            int salesOrderId = -1;
            try
            {
                ArrayList lineItemList = ( ArrayList ) session.getAttribute ( "lineItems" );

                dbTransaction = DBTransaction.getInstance ();
                dbTransaction.begin ();
                salesOrder.setIsSample ( ( isSample == 0 ) ? true : false );

                //Save the salesOrder details & get the salesOrderId
                salesOrder.setEnteredById ( user.getUserId () );
                salesOrder.setEnteredByName ( user.getFirstName () + " " + user.getLastName () );

                salesOrderId = SalesOrderDAO.saveSalesOrder ( dbTransaction, salesOrder );
                salesOrder.setSalesOrderId ( salesOrderId );
                salesOrder.setEnteredDate ( StringUtils.formatDateToString ( new Date ( System.currentTimeMillis () ) ) );
                String contactPerson = salesOrder.getContactPerson ();
                if ( contactPerson.equals ( salesOrder.getCustomerName () ) )
                {
                    SalesOrderDAO.updateAddress ( dbTransaction, salesOrder.getSalesOrderId (), salesOrder.getPhoneNumber (), salesOrder.getFaxNumber (), salesOrder.getEmail (), salesOrder.getContactPerson () );
                }
                else
                {
                    CustomerDAO.updateContactPersonDetails (dbTransaction, salesOrder.getCustomerId(),salesOrder.getContactPerson(),
                                                    salesOrder.getPhoneNumber(),
                                                    salesOrder.getCellNumber(),
                                                    salesOrder.getFaxNumber(),
                                                    salesOrder.getEmail (),
                                                    "");
                }
                SalesOrderDAO.insertLineItems ( dbTransaction, salesOrderId, lineItemList, user.getUserId (), salesOrder.getIsSample());

                // Updates booking date in COOL and CCOL tables and sets them to the Booking Date entered. As Booking Date is now a editable field these tables needs to be updated.
                SalesOrderDAO.updateLineItemBookingDates(dbTransaction, salesOrder);

                alarm = SalesOrderDAO.createAlarm( dbTransaction, user, salesOrder, request.getHeader ( "HOST" ) );

                holdsAuditTrail = SalesOrderDAO.setCustomerHolds( dbTransaction, user, lineItemList, salesOrder.getCustomerId(), salesOrderId, salesOrder.getIsSample() );
                status = SalesDAO.loadOrderStatus ( dbTransaction, salesOrderId );

                //Insert the details in the audit trail
                SalesDAO.updateSalesAuditTrail ( dbTransaction, salesOrderId, user.getUserId (), "Created new sales order" + holdsAuditTrail, "###" + salesOrder.getComments () );

                //Insert BankInfo record in Bank_Table while creating SalesOrder itself
                SalesOrderDAO.insertBankInfo ( dbTransaction, salesOrderId );

                success = true;

                request.setAttribute ( "salesOrderId", Integer.toString ( salesOrderId ) );
                request.setAttribute ( "salesOrderNo", salesOrder.getSalesOrderNo () );

            }
            catch ( ScalarException se )
            {
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SALES_ORDER_DETAILS );
                errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Sales Order Details " );
                session.setAttribute ( SessionKeys.ERROR_REPORT, se );
            }
            finally
            {
                if ( success == true )
                {
                    dbTransaction.commit ();
                    try {
                        String filesubgroupauto = request.getParameter(attachFileTag.PARAM_FILE_SUB_GROUP_AUTO);
                        if(filesubgroupauto != null && filesubgroupauto.trim().length() > 0) {
                            AttachFileDAO.updateFileSubGroup(null, filesubgroupauto, salesOrder.getSalesOrderNo());
                        }
                    } catch (Exception e) {
                        errors.put("Error in attaching files", "Please attach again");
                    }
                    try {
                        String commentsgroupidauto = request.getParameter(InternalCommentsTag.PARAM_COMMENTS_GROUP_ID_AUTO);
                        if(commentsgroupidauto != null && commentsgroupidauto.trim().length() > 0) {
                            InternalCommentsDAO.updateCommentsGroupId(null, commentsgroupidauto, "SalesOrder-" + salesOrder.getSalesOrderNo());
                        }
                    } catch (Exception e) {
                        errors.put("Error in Internal Comments", "Please enter again");
                    }
                    if ( isSample == 1 )
                    {
                        if ( status.trim ().length () == 0 )
                        {
                            errors.put ( "SalesOrder = " + salesOrder.getSalesOrderNo (), "Saved and Approved Successfully" );
                        }
                        else
                        {
                            errors.put ( "SalesOrder = " + salesOrder.getSalesOrderNo (), "Saved Successfully" );
                        }

                        //errors.put ( "Email ", " has been sent to all approvers" );

                        errors.put ( "View/Print ", "Click here to <a href='javascript:openSalesOrder();' onmouseover=\"window.status='Click here to View/print sales order';return true\" onmouseout=\"window.status='';return true\"> view/print </a>Sales Order Details" );
                        if ( user.getUserType() == Constants.USER_TYPE_CHIPTRAC )
                        {
                            String str= "/"+ConfigManager.getChipTracContext()+"/approveOrder.do?salesOrderId="+request.getAttribute("salesOrderId")+"&isSample="+request.getParameter("isSample");
                            if ( status.trim ().length () > 0 )
                            {
                                errors.put ( "Approve", "Click here to <a href='"+str+"'onmouseover=\"window.status='Click here to Approve sales order';return true\" onmouseout=\"window.status='';return true\"> approve </a>Sales Order" );
                            }
                        }
                    }
                    else
                    {
                        if ( status.trim ().length () == 0 )
                        {
                            errors.put ( "SampleOrder = " + salesOrder.getSalesOrderNo (), "Saved and Approved Successfully" );
                        }
                        else
                        {
                            errors.put ( "SampleOrder = " + salesOrder.getSalesOrderNo (), "Saved Successfully" );
                        }

                        errors.put ( "View/Print ", "Click here to <a href='javascript:openSalesOrder();' onmouseover=\"window.status='Click here to View/print sales order';return true\" onmouseout=\"window.status='';return true\"> view/print </a>Sample Order Details" );
                        if ( user.getUserType() == Constants.USER_TYPE_CHIPTRAC )
                        {
                            String str= "/"+ConfigManager.getChipTracContext()+"/approveOrder.do?salesOrderId="+request.getAttribute("salesOrderId")+"&isSample="+request.getParameter("isSample");
                            if ( status.trim ().length () > 0 )
                            {
                                errors.put ( "Approve", "Click here to <a href='"+str+"'onmouseover=\"window.status='Click here to Approve sample order';return true\" onmouseout=\"window.status='';return true\"> approve </a>Sample Order" );
                            }
                        }
                    }

                    try
                    {
                        //Notify all the reciepents
                        //alarm.setRecipients ( AlarmDAO.loadRecipientsWithBoardKitChipAccess ( Integer.parseInt ( ( String ) request.getAttribute ( "salesOrderId" ) ), alarm ) );
                        if ( salesOrder.getSalesPerson() != null && salesOrder.getSalesPerson().length() > 0 )
                        {
                            SalesPerson salesPerson = NewCustomerDAO.getSalesPersonDetails( null, salesOrder.getSalesPerson() );
                            if ( salesPerson != null && salesPerson.isSalesAckMail() )
                            {
                                if ( salesPerson.getAddress() != null && salesPerson.getAddress().getEmail() != null && salesPerson.getAddress().getEmail().trim().length() > 0 )
                                {
                                    alarm.addRecipient ( new AlarmUser( salesPerson.getSalesPerson (), salesPerson.getAddress().getEmail().trim() ) );
                                }
                            }
                        }
                        salesOrderStatus = SalesDAO.loadStatus( null, salesOrder.getSalesOrderId() );
                        if( salesOrderStatus != null && salesOrderStatus.indexOf( Constants.SALESORDER_STATUS_HOLD ) >= 0  )
                        {
                            salesOrderStatus = Constants.SALESORDER_STATUS_HOLD;
                        }
                        if( salesOrder.getIsSample() )
                        {
                            alarm.setSubject( "Sample Order Notification - SampleOrder No.: " + salesOrder.getSalesOrderNo() + " - Customer: " + salesOrder.getCustomerName() + " - Status: " + salesOrderStatus + " -- ACTIVATED");
                        }
                        else
                        {
                            alarm.setSubject( "Sales Order Notification - SO No.: " + salesOrder.getSalesOrderNo() + " - Customer: " + salesOrder.getCustomerName() + " - Status: " + salesOrderStatus + " -- ACTIVATED" );
                        }
                        alarm.notifyAllRecipients ( SalesOrder.getHtmlView ( Integer.parseInt ( ( String ) request.getAttribute ( "salesOrderId" ) ) ) );

                        if( status.trim().length() == 0 )
                        {
                            SalesDAO.updateAlarmAndSendMailWithChangeSummary ( "", salesOrder.getSalesOrderId() , true, user, "" );
                            SalesOrderHelper.notifyApprovedSalesOrderInfo ( salesOrder.getSalesOrderId() );
                            errors.put ( "Email ", " has been sent Successfully" );
                        }

                        //SalesOrderHelper.notifyFinanceReasonCode ( salesOrder.getSalesOrderId() );
                    }
                    catch ( Exception e )
                    {
                        e.printStackTrace();
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SENDING_MAILS_TO_APPROVERS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Send Mail to all Approvers " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, e );
                    }
                    try
                    {
                        InternalCommentsAction.notifiyInternalComments( "SalesOrder-" + salesOrder.getSalesOrderNo(), null, salesOrderId, alarm );
                    }
                    catch ( Exception e )
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not send Internal Comments notification" );
                    }
                }
                else
                {
                    dbTransaction.rollback ();

                    if ( isSample == 1 )
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SALES_ORDER_DETAILS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Sales Order Details " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, null );
                    }
                    else
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SALES_ORDER_DETAILS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Sales Order Details " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, null );
                    }
                }
            }

            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.MESSAGES, errors );
            }
            
            salesOrderMap.remove( selectedCustomer );

        }
        else if ( "loadFreightInstructions".equals ( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
            }
            ArrayList lineItems = null;
            String freightInstructions = null;
            try
            {
                freightInstructions = NewSalesOrderDAO.loadSelectedFreightInstructions( null, subform.getFreightInstructionsId() );
            }
            catch ( ScalarException e )
            {
                System.out.println ( "Exception While loading selected freight Instructions" );
                e.printStackTrace();
            }
            subform.setFreightInstructions ( freightInstructions );

            int someValue = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample ).size ();
            if ( someValue == 0 )
            {
                lineItems = getLineItems ( session, isSample);
                request.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
            }
            else
            {
                lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );
                session.setAttribute ( "lineItems", lineItems );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( lineItems ) );
                session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

                subform.setSalesTaxAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "salesTax" ) ) );
                subform.setSubTotalAsDouble ( Double.parseDouble ( ( String ) request.getAttribute ( "subTotal" ) ) );
                subform.setOrderTotalAsDouble ( subform.getSubTotalAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSalesTaxAsDouble () );
            }
            salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            request.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );
            return ( mapping.findForward ( "salesOrder" ) );
        } // End of loadFreightInstructions
        if ( user.getUserType() == Constants.USER_TYPE_CUSTOMER )
        {
            return ( mapping.findForward ( "changeOrderSearch" ) );
        }
        else
        {
            return ( mapping.findForward ( "successSalesOrder" ) );
        }
    }

    public static ArrayList loadLineItems ( HttpServletRequest request, int customerId, HashMap errors, HashMap info, boolean checkLimits, int isSample ) throws ScalarException
    {
        HttpSession session = request.getSession ();
        String action = request.getParameter ( "action" );
        String[] lineItem = request.getParameterValues ( "lineItemNo" );
        String[] poLineItem = request.getParameterValues ( "poLineItemNo" );
        String[] manufacturingPartNo = request.getParameterValues ( "manufacturingPartNo" );
        String[] quantity = request.getParameterValues ( "quantity" );
        String[] leadTime = request.getParameterValues ( "leadTime" );        
        String[] oldQty = request.getParameterValues ( "oldQty" );
        String[] requestDate = request.getParameterValues ( "requestDate" );
        String[] unitPrice = request.getParameterValues ( "unitPriceAsDouble" );
        String[] lineItemDescription = request.getParameterValues ( "lineItemDescription" );
        String[] customerPartNo = request.getParameterValues ( "customerPartNo" );
        String[] newCustPartNo = request.getParameterValues ( "newCustomerPartNo" );
        String[] customPriceField1 = request.getParameterValues ( "customPriceField1" );
        String[] customTextField1 = request.getParameterValues ( "customTextField1" );
        String[] labelNumber = null;
        String salesTaxType = request.getParameter ( "salesTaxType" );
        if ( ( salesTaxType.equalsIgnoreCase ( "-1" ) ) == true )
        {
            salesTaxType = request.getParameter ( "newSalesState" );
        }
        float taxvalue = SalesOrderDAO.getTaxValue ( null, salesTaxType );
        Float ff = new Float ( taxvalue );
        double tax = ff.doubleValue ();
        ArrayList lineItemsList = new ArrayList ();
        LineItem lineItemInfo = null;
        String zeroPrice = "";
        String productPrice = "";
        String tempLeadItem="";
        int totalQty = 0;
        float subTotal = 0.0f;
        double salesTax = 0.0;
        double finalSubTotal = 0.0;
        int tempLineItemNo = 0;

        boolean found = false;

        for ( int i = 0; i < manufacturingPartNo.length; i++ )
        {
            if ( lineItem[i].trim ().equals ( "" ) )
                lineItem[i] = "0";

            if ( ( manufacturingPartNo[i] != null ) && ( !manufacturingPartNo[i].equals ( "" ) ) )
            {
                if ( quantity[i].equals ( "" ) )
                {
                    quantity[i] = "0";
                }
                if ( unitPrice[i].equals ( "" ) )
                {
                    unitPrice[i] = "0.0";
                }
                if(leadTime == null || leadTime[i] == null )
                {
                    tempLeadItem = "";
                }
                else
                {
                    tempLeadItem = leadTime[i];
                }
                lineItemInfo = SalesOrderDAO.loadLineItemInfo ( customerId, Integer.parseInt ( lineItem[i] ),
                                                                null,
                                                                manufacturingPartNo[i],
                                                                requestDate[i], tempLeadItem,
                                                                Integer.parseInt ( quantity[i] ),
                                                                StringUtils.formatToFloat ( unitPrice[i] ), isSample);
                if ( lineItemInfo == null )
                {
                    errors.put ( "LineItem No " + lineItem[i], "is not having valid partnumbers, please enter valid partnumbers" );
                }
                if ( lineItemInfo == null )
                {
                    lineItemInfo = new LineItem ();
                    lineItemInfo.setLineItemNo ( Integer.parseInt ( lineItem[i] ) );
                    lineItemInfo.setManufacturingPartNo ( manufacturingPartNo[i] );
                    lineItemInfo.setLineItemDescription ( lineItemDescription[i].trim () );
                    lineItemInfo.setCustomerPartNo ( customerPartNo[i] );
                    lineItemInfo.setQuantity ( Integer.parseInt ( quantity[i] ) );
                    lineItemInfo.setUnitPrice ( StringUtils.formatToFloat ( unitPrice[i] ) );
                    lineItemInfo.setUnitPriceAsDouble ( Double.parseDouble ( unitPrice[i] ) );
                    lineItemInfo.setRequestDate ( requestDate[i] );
                }
                else
                {
                    if ( requestDate[i].trim ().length () == 0 )
                    {
                        errors.put ( "LineItem No " + lineItem[i], "Please enter Request  Dock Date." );
                    }
                }
                lineItemInfo.setPoLineItemNo ( Integer.parseInt ( poLineItem[i] ) );
                zeroPrice = request.getParameter ( "zeroPrice" + lineItem[i] );
                lineItemInfo.setZeroPrice ( ( zeroPrice != null ) ? true : false );
                //To set value to oldQty when it zero for the first time
                if ( "0".equals ( oldQty[i] ) )
                {
                    oldQty[i] = quantity[i];
                }
                productPrice = SalesOrderDAO.loadOldQtyPrice ( null, lineItemInfo.getProductId (), customerId, Integer.parseInt ( oldQty[i] ),lineItemInfo.getRequestDate(), isSample);
                if ( ( ( StringUtils.formatToFloat ( unitPrice[i] ) != 0.0 ) || zeroPrice != null ) /*&& ( isSample == 1 )*/ ) //sample orders may have unit price
                {
                    if ( ( quantity[i].equalsIgnoreCase ( oldQty[i] ) ) || ( !unitPrice[i].equalsIgnoreCase ( productPrice ) ) )
                    {
                        lineItemInfo.setUnitPrice ( StringUtils.formatToFloat ( Double.toString ( Double.parseDouble ( unitPrice[i] ) ) ) );
                        lineItemInfo.setUnitPriceAsDouble ( Double.parseDouble ( unitPrice[i] ) );
                        double unit_price = Double.parseDouble ( unitPrice[i] );
                        double amt = ( Integer.parseInt ( quantity[i] ) ) * unit_price;
                        lineItemInfo.setAmountAsDouble ( amt );
                    }
                }
                //we have moved whether sample SO is default to zero price or not to configuration..we may have price for sample orders.
                /*if ( isSample == 0 )
                {
                    lineItemInfo.setUnitPrice ( 0 );
                    lineItemInfo.setUnitPriceAsDouble( 0 );
                    lineItemInfo.setAmount ( 0 );
                    lineItemInfo.setAmountAsDouble(0);
                }*/
                //If the taxable is selected then setTaxable to true to check the checkbox and calculate salestax for that lineItem AND add it to sales Tax

                lineItemInfo.setIsExpedite ( ( request.getParameter ( "expediteFee" + lineItem[i] ) != null ) ? true : false );

                if ( request.getParameter ( "isTaxable" + lineItem[i] ) != null )
                {
                    lineItemInfo.setIsTaxable ( true );
                    salesTax = salesTax + ( lineItemInfo.getAmountAsDouble () * ( tax / 100 ) );
                }
                if ( ( lineItemDescription[i] == null ) || ( lineItemDescription[i].trim ().length () == 0 ) )
                {
                    String lItemDesc = null;
                    try
                    {
                        lItemDesc = SalesOrderDAO.getLineItemDescriptionByMfgPartNumber ( manufacturingPartNo[i] );
                        lItemDesc = ( ( lItemDesc == null ) ? "" : lItemDesc );
                        lineItemInfo.setLineItemDescription ( lItemDesc );
                    }
                    catch ( ScalarException se )
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SALES_ORDER_DETAILS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Sales Order Details " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, se );
                    }

                }
                else
                {
                    lineItemInfo.setLineItemDescription ( lineItemDescription[i] );
                }
                lineItemInfo.setCustomerPartNo ( customerPartNo[i] );
                lineItemInfo.setNewCustomerPartNo ( newCustPartNo[i] );
                lineItemInfo.setCustomPriceField1(customPriceField1!= null ? Double.parseDouble(customPriceField1[i]) : 0);
                lineItemInfo.setCustomTextField1(customTextField1 != null ? customTextField1[i] : null);
                //calculate total quantity and amount and set it in request
                totalQty = totalQty + lineItemInfo.getQuantity ();
                finalSubTotal = finalSubTotal + lineItemInfo.getAmountAsDouble ();
                try
                {
                    lineItemInfo.setAmount ( Float.parseFloat ( StringUtils.formatAmountWithNoOfDecimals ( lineItemInfo.getAmount ()) ) );
                }
                catch ( NumberFormatException ignore ) {}
                request.setAttribute ( "totalQty", Integer.toString ( totalQty ) );
                request.setAttribute ( "salesTax", Double.toString ( salesTax ) );
                request.setAttribute ( "subTotal", Double.toString ( finalSubTotal ) );
                if(Integer.parseInt(lineItem[i]) > tempLineItemNo )
                {
                    tempLineItemNo = Integer.parseInt(lineItem[i]);
                }
                lineItemsList.add ( lineItemInfo );
            }
            else
            {
                found = true;
            }
        }
        request.setAttribute ( "maxLineItemNo", Integer.toString ( tempLineItemNo + 1 ) );
        request.setAttribute ( "Errors", errors );
        request.setAttribute ( "Info", info );
        //To reset the Line Item no and PO Line Item no when mfg part number is null.
        if ( found == true )
        {
            LineItem tempLineItem = null;
            int i = 0;
            for ( i = 0; i < lineItemsList.size(); i++ )
            {
                tempLineItem = ( LineItem ) lineItemsList.get( i );
                tempLineItem.setLineItemNo ( i + 1 );
                tempLineItem.setPoLineItemNo ( i + 1 );
            }
            request.setAttribute ( "maxLineItemNo", Integer.toString ( i + 1) );
        }

        return lineItemsList;
    }

    //Separates the line items based on Manufacturing Part Nos and calculates SubTotals.
    public static ArrayList loadLineItemsWithSubTotals ( ArrayList lineItemList )
    {
        ArrayList list = new ArrayList ();
        LinkedHashMap hash = new LinkedHashMap ();
        for ( int i = 0; i < lineItemList.size (); i++ )
        {
            LineItem lineItem = ( LineItem ) lineItemList.get ( i );
            String mfgPartNumber = lineItem.getManufacturingPartNo ();
            if ( !( hash.containsKey ( mfgPartNumber ) ) )
            {
                hash.put ( mfgPartNumber, new ArrayList () );
            }
            ArrayList arrList = ( ArrayList ) hash.get ( mfgPartNumber );
            arrList.add ( lineItem );
        }
        Iterator iterator = hash.keySet ().iterator ();
        LinkedHashMap hashMap = new LinkedHashMap ();

        while ( iterator.hasNext () )
        {
            String str = ( String ) iterator.next ();
            ArrayList arrList = ( ArrayList ) hash.get ( str );
            SubTotal subTotal = new SubTotal();

            double subTotalAmt = 0.0;
            int subTotalQty = 0;
            int subTotalProposedQty = 0;
            for ( int i = 0; i < arrList.size (); i++ )
            {
                subTotalAmt = subTotalAmt + ( ( LineItem ) arrList.get ( i ) ).getAmountAsDouble ();
                subTotalQty = subTotalQty + ( ( LineItem ) arrList.get ( i ) ).getQuantity ();
                subTotalProposedQty = subTotalProposedQty + ( ( LineItem ) arrList.get ( i ) ).getQuotedQuantity();
            }
            subTotal.setSubTotalQty ( Integer.toString ( subTotalQty ) );
            subTotal.setSubTotalProposedQty( Integer.toString( subTotalProposedQty ) );

            subTotal.setSubTotalAmt ( StringUtils.formatAmountWithNoOfDecimals ( subTotalAmt) );
            hashMap.put ( arrList, subTotal );
        }
        list.add ( hashMap );

        return list;
    }

    //To provide New Sales Tax State functionality
    private void addNewSalesTaxState ( HttpServletRequest request, HttpSession session, HashMap errors, SalesOrderForm subform )
    {
        String state1 = null;
        String value1 = null;
        String[] newSalesState = new String[1];
        String[] newSalesTax = new String[1];
        boolean checkstate = false;

        try
        {
            state1 = request.getParameter ( "newSalesState" );
            value1 = request.getParameter ( "newSalesTax" );
            String salesTaxType = request.getParameter ( "salesTaxType" );

            if ( "-1".equals ( salesTaxType ) )
            {
                if ( state1 != null )
                {
                    state1 = state1.trim ();
                }
                checkstate = SalesOrderDAO.doesSalesTaxStateExist ( null, state1 );

                if ( checkstate == false )
                {
                    if ( ( state1 != null && state1.length () > 0 ) && ( value1 != null && value1.length () > 0 ) )
                    {
                        newSalesState[0] = state1.trim ();
                        newSalesTax[0] = value1.trim ();

                        SalesDAO.saveSalesTaxes ( newSalesState, newSalesTax, " " );
                        ArrayList salesStatesList = ( ArrayList ) session.getAttribute ( "salesTaxes" );


                        salesStatesList.add ( new LabelValueBean ( state1 + " - " + value1, state1 ) );
                        session.setAttribute ( "salesTaxes", salesStatesList );
                        subform.setSalesTaxType ( state1 );

                        value1 = null;
                    }
                }
                else
                {
                    errors.put ( "The State '" + state1 + "' already exists", null );
                    request.setAttribute ( "otherstateadded", "false" );
                    request.setAttribute ( "newsalesstate", state1 );
                    request.setAttribute ( "newsalesvalue", value1 );
                }
            }
        }
        catch ( Exception e )
        {
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_NEW_SALES_TAX_STATE );
            errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
            session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save New Sales Tax State" );
            session.setAttribute ( SessionKeys.ERROR_REPORT, e );
        }
        request.setAttribute ( "Errors", errors );
    }

    public static ArrayList getLineItems(HttpSession session, int isSample) throws ScalarException
    {
        ArrayList lineItems = new ArrayList ();
        boolean isDefaultZeroPrice = false;
        if ( isSample == 0 )
        {
            isDefaultZeroPrice = ConfigManager.isDefaultZeroPriceForSampleSO();
        }
        for ( int i = 1; i < 6; i++ )
        {
            LineItem lineItem = new LineItem ();
            lineItem.setLineItemNo ( i );
            lineItem.setPoLineItemNo ( i );
            lineItem.setZeroPrice( isDefaultZeroPrice );
            lineItems.add ( lineItem );
        }
        session.setAttribute ( "maxLineItemNo", "6" );

        return lineItems;
    }

    //To optimise code for adding New Shipping Method which is used more than once
    private void addNewShippingMethod ( HttpServletRequest request, HttpSession session, HashMap errors, HashMap info, SalesOrderForm subform, SalesOrder salesOrderFromMap )
    {
        String customerId = request.getParameter ( "customerId" );
        int custIdInt = 0;
        String method = null;
        String account = null;
        boolean checkmethodexist = true;
        int customerIdvalue = -1;
        String newShippingMethodLabel = null;
        String shippingMethodLabel = null;

        if ( customerId != null )
        {
            session.setAttribute ( "addShippingMethodCustomerId", customerId );
        }
        else
        {
            customerId = ( String ) session.getAttribute ( "addShippingMethodCustomerId" );
        }

        String shippingMethod = subform.getShippingMethod ();
        if ( "-2".equalsIgnoreCase ( shippingMethod ) == true )
        {
            try
            {
                method = request.getParameter ( "newshippingMethod" );
                account = request.getParameter ( "newshippingAccount" );
                customerIdvalue = Integer.parseInt ( customerId );
                if ( method != null )
                {
                    method = method.trim ();
                }
                if ( account != null )
                {
                    account = account.trim ();
                }
                checkmethodexist = CustomerDAO.doesShippingMethodExist ( null, customerIdvalue, method, account );

                if ( checkmethodexist == false )
                {
                    if ( !( ( method.equals ( "" ) ) && ( account.equals ( "" ) ) ) )
                    {
                        try
                        {
                            if ( method != null )
                            {
                                method = method.trim ();
                            }
                            if ( account != null )
                            {
                                account = account.trim ();
                            }
                            CustomerDAO.insertShippingMethod ( null, customerIdvalue, method, account );
                            ArrayList shippingMethodList = salesOrderFromMap.getShippingMethods();
                            //To get shiping account along with shipping method
                            shippingMethodList.add ( new LabelValueBean ( method + "   #   " + account, method + "   #   " + account ) );
                            salesOrderFromMap.setShippingMethods( shippingMethodList );
                            //For removing the values from new shippoing method and account after they have been added to the database
                            subform.setNewshippingAccount ( "" );
                            subform.setNewshippingMethod ( "" );
                            try
                            {
                                newShippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.NewShippingMethod" );
                                if ( newShippingMethodLabel == null )
                                {
                                    newShippingMethodLabel = Labels.DEFAULT_NEW_SHIPPING_METHOD_LABEL;
                                }
                            }
                            catch ( NullPointerException e )
                            {
                                 newShippingMethodLabel = Labels.DEFAULT_NEW_SHIPPING_METHOD_LABEL;
                            }
                            info.put ( newShippingMethodLabel+" has been stored in database successfully", null );
                        }

                        catch ( ScalarException se )
                        {
                            try
                            {
                                shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                                if ( shippingMethodLabel == null )
                                {
                                    shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                                }
                            }
                            catch ( NullPointerException e )
                            {
                                shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                            }
                            errors.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not Save "+shippingMethodLabel+" Value."+ method );
                            se.printStackTrace ();
                        }
                    }
                    subform.setShippingMethodName ( method + "   #   " + account );
                    subform.setShippingAccount ( method + "   #   " + account );
                    subform.setShippingMethod ( method + "   #   " + account );
                    salesOrderFromMap.setShippingMethod( subform.getShippingMethod() );
                }
                else
                {
                    try
                    {
                        shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                        if ( shippingMethodLabel == null )
                        {
                            shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                    errors.put ( method +" " +shippingMethodLabel+" already Exists ,Please enter another "+shippingMethodLabel+".", null );
                }
            }
            catch ( Exception e )
            {
                e.printStackTrace ();
            }
        }
    }

    private void addNewShippingTerms ( HttpServletRequest request, HttpSession session, HashMap errors, HashMap info, SalesOrderForm subform )
    {
        String shippingTerms = null;
        String newShippingTerms = null;
        boolean checkmethodexist = true;

        shippingTerms = subform.getShippingTerms ();

        if ( "-2".equalsIgnoreCase ( shippingTerms ) == true )
        {
            try
            {
                newShippingTerms = request.getParameter ( "newShippingTerms" );

                if ( newShippingTerms != null )
                {
                    newShippingTerms = newShippingTerms.trim ();
                }
                else
                {
                    newShippingTerms = "";
                }
                if ( newShippingTerms != null && newShippingTerms.trim ().length () != 0 )
                {
                    checkmethodexist = SalesDAO.doesShippingTermsExist ( null, newShippingTerms );

                    if( Constants.CLIENT_NAME_AIRGO.equalsIgnoreCase( ConfigManager.getClientNameAirgo() ) && Constants.SALESORDER_LETTER_OF_CREDIT.equalsIgnoreCase ( newShippingTerms ) )
                    {
                        checkmethodexist = true;
                    }

                    if ( checkmethodexist == false )
                    {
                        try
                        {
                            SalesDAO.insertShippingTerms ( null, newShippingTerms );
                            ArrayList shippingTermsList = ( ArrayList ) session.getAttribute ( "allShippingTerms" );
                            shippingTermsList.add ( newShippingTerms );
                            session.setAttribute ( "allShippingTerms", shippingTermsList );
                            info.put ( "New Pay Terms are added successfully", null );
                            subform.setShippingTerms ( newShippingTerms );
                        }
                        catch ( ScalarException se )
                        {
                            String shippingMethodLabel = null;
                            try
                            {
                                shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                                if ( shippingMethodLabel == null )
                                {
                                    shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                                }
                            }
                            catch ( NullPointerException e )
                            {
                                shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                            }
                            errors.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not Save "+shippingMethodLabel+" Value."+ newShippingTerms );
                            se.printStackTrace ();
                        }
                    }
                    else
                    {
                        errors.put ( newShippingTerms + " " + ERROR_SHIPPING_TERMS_EXISTS, null );
                    }
                }
            }
            catch ( Exception e )
            {
                e.printStackTrace ();
            }
        }
        if( Constants.CLIENT_NAME_AIRGO.equalsIgnoreCase( ConfigManager.getClientNameAirgo() ) )
        {
            if( ! Constants.SALESORDER_LETTER_OF_CREDIT.equalsIgnoreCase ( subform.getShippingTerms() ) )
            {
                subform.setLetterOfCreditNo( null );
                subform.setLcIssuingBank( null );
            }
        }
        else
        {
            subform.setLetterOfCreditNo( null );
            subform.setLcIssuingBank( null );
        }
    }

    public static void addNewDeliveryTerms ( HttpServletRequest request, HttpSession session, HashMap errors, HashMap info, SalesOrderForm subform )
    {
        String deliveryTerms = null;
        String newDeliveryTerms = null;
        boolean checkTermsexist = false;

        deliveryTerms = subform.getDeliveryTerms ();
        if ( "-2".equalsIgnoreCase ( deliveryTerms ) == true )
        {
            try
            {
                newDeliveryTerms = request.getParameter ( "newDeliveryTerms" );
                if ( newDeliveryTerms != null )
                {
                    newDeliveryTerms = newDeliveryTerms.trim ();
                }
                else
                {
                    newDeliveryTerms = "";
                }
                if ( newDeliveryTerms != null && newDeliveryTerms.trim ().length () != 0 )
                {
                    String deliveryTermsLabel = null;
                    try
                    {
                        deliveryTermsLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.DeliveryTerms" );
                        if ( deliveryTermsLabel == null )
                        {
                            deliveryTermsLabel = Labels.DEFAULT_DELIVERY_TERMS_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        deliveryTermsLabel    = Labels.DEFAULT_DELIVERY_TERMS_LABEL;
                    }
                    ArrayList deliveryTermsList = ( ArrayList ) session.getAttribute ( "allDeliveryTerms" );
                    for ( int i = 0; i < deliveryTermsList.size(); i++ )
                    {
                        if ( newDeliveryTerms.equalsIgnoreCase( ( String )deliveryTermsList.get(i) ) )
                        {
                            checkTermsexist = true;
                            break;
                        }
                    }
                    if ( !checkTermsexist )
                    {
                        try
                        {
                            SalesDAO.insertDeliveryTerms ( null, newDeliveryTerms );
                            deliveryTermsList.add ( newDeliveryTerms );
                            session.setAttribute ( "allDeliveryTerms", deliveryTermsList );
                            info.put ( deliveryTermsLabel+ " added successfully", null );
                            subform.setDeliveryTerms ( newDeliveryTerms );
                        }
                        catch ( ScalarException se )
                        {

                            errors.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not Save "+deliveryTermsLabel+" Value."+ newDeliveryTerms );
                            se.printStackTrace ();
                        }
                    }
                    else
                    {
                        errors.put ( newDeliveryTerms + " " + deliveryTermsLabel +" already Exists, Please enter another "+deliveryTermsLabel, null );
                    }
                }
            }
            catch ( Exception e )
            {
                e.printStackTrace ();
            }
        }
    }
    public static void addNewShippingInstructions( HttpServletRequest request, HttpSession session, HashMap errors, HashMap info, SalesOrderForm subform )
    {
        int shippingInstructionsId  = subform.getShippingInstructionsId();
        String shippingInstructions = subform.getShippingInstructions();
        boolean checkInstructionsexist = false;
        if ( shippingInstructionsId == -2  && shippingInstructions != null && shippingInstructions.trim().length() > 0 )
        {
            ArrayList shippingInstructionsList = ( ArrayList )session.getAttribute("shippingInstructions");
            for (int i = 0; i < shippingInstructionsList.size(); i++)
            {
                LabelValueBean labelValueBean = (LabelValueBean) shippingInstructionsList.get(i);
                if ( ( shippingInstructions.trim()).equalsIgnoreCase( labelValueBean.getLabel().trim() ) )
                {
                    checkInstructionsexist = true;
                    break;
                }
            }
            if ( !checkInstructionsexist )
            {
                try
                {
                    shippingInstructionsId = NewSalesOrderDAO.saveShippingInstructions( null, shippingInstructions );
                    subform.setShippingInstructionsId( shippingInstructionsId );
                    shippingInstructionsList.add( new LabelValueBean( shippingInstructions, shippingInstructionsId+"" ) );
                    info.put ( "New Shipping Instructions added successfully", null );
                }
                catch( Exception e)
                {
                    errors.put("Shipping Instructions ","Could not save Shipping Instructions" );
                }
            }
            else
            {
                    errors.put("Shipping Instructions already exists, Please enter another Shipping Instructions ", null );
            }
        }
    }

    private ArrayList loadShippingAddresses ( ArrayList shippingAddresses )
    {
        Address address = null;
        ArrayList shippingList = new ArrayList ();
        for ( int i = 0; i < shippingAddresses.size (); i++ )
        {
            address = ( Address ) shippingAddresses.get ( i );
            int shippingAddressId = address.getAddressId ();
            String addrStr = "";
            if ( ( address.getAddress1 () != null ) && ( address.getAddress1 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new LabelValueBean ( address.getAddress1 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress2 () != null ) && ( address.getAddress2 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new LabelValueBean ( address.getAddress2 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress3 () != null ) && ( address.getAddress3 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new LabelValueBean ( address.getAddress3 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress4 () != null ) && ( address.getAddress4 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new LabelValueBean ( address.getAddress4 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getCity () != null ) && ( address.getCity ().trim ().length () != 0 ) )
            {
                shippingList.add ( new LabelValueBean ( address.getCity (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
            {
                addrStr = addrStr + address.getState ();
            }
            if ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) )
            {
                if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
                {
                    addrStr = addrStr + "-";
                }
                addrStr = addrStr + address.getZipCode ();
            }
            if ( ( address.getCountry () != null ) && ( address.getCountry ().trim ().length () != 0 ) )
            {
                if ( ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) ) || ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) ) )
                {
                    addrStr = addrStr + ",";
                }
                addrStr = addrStr + address.getCountry ();
            }
            if ( !( "".equals ( addrStr ) ) )
            {
                shippingList.add ( new LabelValueBean ( addrStr, Integer.toString ( address.getAddressId () ) ) );
            }
            shippingList.add ( new LabelValueBean ( "", Integer.toString ( address.getAddressId () ) ) );
        }
        return shippingList;
    }
    public static void loadShippingAddress( Address address, ArrayList shippingList, SalesOrder salesOrderFromMap ){

        String addrStr = "";

        if ( ( address.getAddress1 () != null ) && ( address.getAddress1 ().trim ().length () != 0 ) )
        {
            shippingList.add ( new LabelValueBean ( address.getAddress1 (), Integer.toString ( address.getAddressId () ) ) );
        }
        if ( ( address.getAddress2 () != null ) && ( address.getAddress2 ().trim ().length () != 0 ) )
        {
            shippingList.add ( new LabelValueBean ( address.getAddress2 (), Integer.toString ( address.getAddressId () ) ) );
        }
        if ( ( address.getAddress3 () != null ) && ( address.getAddress3 ().trim ().length () != 0 ) )
        {
            shippingList.add ( new LabelValueBean ( address.getAddress3 (), Integer.toString ( address.getAddressId () ) ) );
        }
        if ( ( address.getAddress4 () != null ) && ( address.getAddress4 ().trim ().length () != 0 ) )
        {
            shippingList.add ( new LabelValueBean ( address.getAddress4 (), Integer.toString ( address.getAddressId () ) ) );
        }
        if ( ( address.getCity () != null ) && ( address.getCity ().trim ().length () != 0 ) )
        {
            shippingList.add ( new LabelValueBean ( address.getCity (), Integer.toString ( address.getAddressId () ) ) );
        }
        if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
        {
            addrStr = addrStr + address.getState ();
        }
        if ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) )
        {
            if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
            {
                addrStr = addrStr + "-";
            }
            addrStr = addrStr + address.getZipCode ();
        }
        if ( ( address.getCountry () != null ) && ( address.getCountry ().trim ().length () != 0 ) )
        {
            if ( ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) ) || ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) ) )
            {
                addrStr = addrStr + ",";
            }
            addrStr = addrStr + address.getCountry ();
        }
        if ( !( "".equals ( addrStr ) ) )
        {
            shippingList.add ( new LabelValueBean ( addrStr, Integer.toString ( address.getAddressId () ) ) );
        }
        shippingList.add ( new LabelValueBean ( "", Integer.toString ( address.getAddressId () ) ) );
        ArrayList shippingContactPersons = new ArrayList();
        shippingContactPersons.add( address.getContactPerson() );
        salesOrderFromMap.setContactPersonsForShippingAddress( shippingContactPersons );
    }

    public static String getAddressAsString( Address address )
    {
        StringBuffer tempAddress =   new StringBuffer("");
        String address1 = address.getAddress1();
        String address2 = address.getAddress2();
        String address3 = address.getAddress3();
        String address4 = address.getAddress4();
        String city = address.getCity();
        String zipCode= address.getZipCode();
        String state = address.getState();
        String country = address.getCountry();

        if(address1!=null && !(address1.trim().equals("")))
        {
            tempAddress.append(address1);
        }
        if(address2!=null && !(address2.equals("")))
        {
            tempAddress.append(address2);
        }
        if(address3!=null && !(address3.equals("")))
        {
           tempAddress.append(address3);
        }
        if(address4!=null && !(address4.equals("")))
        {
           tempAddress.append(address4);
        }
        if(city!=null && !(city.equals("")))
        {
            tempAddress.append(city);
        }
        if(state!=null && !(state.equals("")))
        {
            tempAddress.append(state);
        }
        if(zipCode!=null && !(zipCode.equals("")))
        {
            tempAddress.append(zipCode);
        }
        if(country!=null && !(country.equals("")))
        {
            tempAddress.append(country);
        }
        return tempAddress.toString();
    }

    public static void addNewFreightInstructions( HttpServletRequest request, HttpSession session, HashMap errors, HashMap info, SalesOrderForm subform )
    {
        int freightInstructionsId  = subform.getFreightInstructionsId();
        String freightInstructions = ( subform.getFreightInstructions() == null ? "" : subform.getFreightInstructions().trim() );
        if ( freightInstructionsId == -2 && !"".equals ( freightInstructions ) )
        {
            try
            {
                ArrayList freightInstructionsList = ( ArrayList )session.getAttribute ( "freightInstructions" );
                int freightInstructionsSize = ( freightInstructionsList == null ? 0 : freightInstructionsList.size() );
                LabelValueBean freightInstructionsBean = null;
                for ( int i=0; i < freightInstructionsSize; i++ )
                {
                    freightInstructionsBean = ( LabelValueBean )freightInstructionsList.get( i );
                    if ( freightInstructionsBean != null && freightInstructions.equalsIgnoreCase( freightInstructionsBean.getLabel() ) )
                    {
                        try
                        {
                            freightInstructionsId = Integer.parseInt ( freightInstructionsBean.getValue() );
                        }
                        catch ( NumberFormatException e )
                        {
                            freightInstructionsId = 0;
                        }
                        break;
                    }
                }
                if ( freightInstructionsId <= 0 )
                {
                    freightInstructionsId = NewSalesOrderDAO.saveFreightInstructions( null, freightInstructions );
                    if ( freightInstructionsList == null )
                    {
                        freightInstructionsList = new ArrayList();
                    }
                    freightInstructions = freightInstructions.length() < 29 ? freightInstructions : freightInstructions.substring(0,25)+"...";
                    int idx = 0;
                    if ( freightInstructionsSize > 0 )
                    {
                          idx = freightInstructionsSize - 1 ;
                    }
                    freightInstructionsList.add( idx, new LabelValueBean( freightInstructions, freightInstructionsId + "" ) );
                }
                subform.setFreightInstructionsId( freightInstructionsId );
                info.put ( "New Freight Instructions added successfully", null );
            } catch( Exception e)
            {
                errors.put("Freight Instructions ","Could not save Freight Instructions" );
            }
        }
    }
}
